const fs = require('fs').promises;
const path = require('path');
const crypto = require('crypto');
const { query, transaction } = require('../config/database');
const multer = require('multer');

class CloudStorageService {
  constructor() {
    this.uploadPath = path.join(__dirname, '../../uploads/cloud');
    this.tempPath = path.join(__dirname, '../../uploads/temp');
    this.maxFileSize = 100 * 1024 * 1024; // 100MB
    this.allowedFileTypes = [
      // 文档
      'pdf', 'doc', 'docx', 'txt', 'md', 'rtf', 'odt', 'pages',
      // 表格
      'xls', 'xlsx', 'csv', 'ods', 'numbers',
      // 演示文稿
      'ppt', 'pptx', 'odp', 'key',
      // 图片
      'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg', 'tiff', 'ico',
      // 音频
      'mp3', 'wav', 'flac', 'aac', 'ogg', 'm4a', 'wma',
      // 视频
      'mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv', 'm4v',
      // 压缩包
      'zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'xz',
      // 代码
      'js', 'ts', 'jsx', 'tsx', 'html', 'css', 'scss', 'less', 'sass',
      'py', 'java', 'cpp', 'c', 'h', 'hpp', 'php', 'rb', 'go', 'rs',
      'swift', 'kt', 'scala', 'r', 'matlab', 'm', 'pl', 'sh', 'ps1',
      'json', 'xml', 'yaml', 'yml', 'toml', 'ini', 'cfg', 'conf',
      'sql', 'bat', 'cmd', 'dockerfile', 'makefile',
      // 其他
      'log', 'txt', 'rtf', 'tex', 'epub', 'mobi'
    ];
  }

  // 初始化存储目录
  async initializeStorage() {
    try {
      await fs.mkdir(this.uploadPath, { recursive: true });
      await fs.mkdir(this.tempPath, { recursive: true });
      console.log('✅ 云盘存储目录初始化完成');
    } catch (error) {
      console.error('❌ 云盘存储目录初始化失败:', error);
      throw error;
    }
  }

  // 生成文件哈希
  generateFileHash(buffer) {
    return crypto.createHash('sha256').update(buffer).digest('hex');
  }

  // 处理文件名编码问题
  processFileName(originalName) {
    let processedName = originalName;
    
    // 如果文件名是Buffer，尝试解码
    if (Buffer.isBuffer(processedName)) {
      processedName = processedName.toString('utf8');
    }
    
    // 如果文件名包含乱码字符，尝试修复
    if (processedName.includes('\\x') || /[\x00-\x1F\x7F-\x9F]/.test(processedName)) {
      try {
        // 尝试从Content-Disposition头解析文件名
        const matches = processedName.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
        if (matches && matches[1]) {
          processedName = matches[1].replace(/['"]/g, '');
          // 尝试解码URL编码的文件名
          try {
            processedName = decodeURIComponent(processedName);
          } catch (e) {
            // 如果解码失败，使用原始名称
          }
        }
      } catch (e) {
        console.warn('无法从Content-Disposition解析文件名，使用原始名称');
      }
    }
    
    // 清理文件名，移除特殊字符但保留中文
    processedName = processedName.replace(/[<>:"/\\|?*]/g, '_');
    
    // 确保文件名不为空
    if (!processedName || processedName.trim() === '') {
      processedName = 'unnamed_file';
    }
    
    return processedName;
  }

  // 生成唯一文件名
  generateUniqueFileName(originalName) {
    const timestamp = Date.now();
    const random = Math.random().toString(36).substring(2, 15);
    const ext = path.extname(originalName);
    return `${timestamp}-${random}${ext}`;
  }

  // 检查文件类型是否允许
  isAllowedFileType(fileName) {
    const ext = path.extname(fileName).toLowerCase().substring(1);
    return this.allowedFileTypes.includes(ext);
  }

  // 获取文件MIME类型
  getMimeType(fileName) {
    const ext = path.extname(fileName).toLowerCase();
    const mimeTypes = {
      // 文档
      '.pdf': 'application/pdf',
      '.doc': 'application/msword',
      '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      '.txt': 'text/plain',
      '.md': 'text/markdown',
      '.rtf': 'application/rtf',
      '.odt': 'application/vnd.oasis.opendocument.text',
      '.pages': 'application/vnd.apple.pages',
      
      // 表格
      '.xls': 'application/vnd.ms-excel',
      '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      '.csv': 'text/csv',
      '.ods': 'application/vnd.oasis.opendocument.spreadsheet',
      '.numbers': 'application/vnd.apple.numbers',
      
      // 演示文稿
      '.ppt': 'application/vnd.ms-powerpoint',
      '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
      '.odp': 'application/vnd.oasis.opendocument.presentation',
      '.key': 'application/vnd.apple.keynote',
      
      // 图片
      '.jpg': 'image/jpeg',
      '.jpeg': 'image/jpeg',
      '.png': 'image/png',
      '.gif': 'image/gif',
      '.bmp': 'image/bmp',
      '.webp': 'image/webp',
      '.svg': 'image/svg+xml',
      '.tiff': 'image/tiff',
      '.ico': 'image/x-icon',
      
      // 音频
      '.mp3': 'audio/mpeg',
      '.wav': 'audio/wav',
      '.flac': 'audio/flac',
      '.aac': 'audio/aac',
      '.ogg': 'audio/ogg',
      '.m4a': 'audio/mp4',
      '.wma': 'audio/x-ms-wma',
      
      // 视频
      '.mp4': 'video/mp4',
      '.avi': 'video/x-msvideo',
      '.mov': 'video/quicktime',
      '.wmv': 'video/x-ms-wmv',
      '.flv': 'video/x-flv',
      '.webm': 'video/webm',
      '.mkv': 'video/x-matroska',
      '.m4v': 'video/x-m4v',
      
      // 压缩包
      '.zip': 'application/zip',
      '.rar': 'application/x-rar-compressed',
      '.7z': 'application/x-7z-compressed',
      '.tar': 'application/x-tar',
      '.gz': 'application/gzip',
      '.bz2': 'application/x-bzip2',
      '.xz': 'application/x-xz',
      
      // 代码
      '.js': 'application/javascript',
      '.ts': 'application/typescript',
      '.jsx': 'text/jsx',
      '.tsx': 'text/tsx',
      '.html': 'text/html',
      '.css': 'text/css',
      '.scss': 'text/scss',
      '.less': 'text/less',
      '.sass': 'text/sass',
      '.py': 'text/x-python',
      '.java': 'text/x-java-source',
      '.cpp': 'text/x-c++src',
      '.c': 'text/x-csrc',
      '.h': 'text/x-chdr',
      '.hpp': 'text/x-c++hdr',
      '.php': 'text/x-php',
      '.rb': 'text/x-ruby',
      '.go': 'text/x-go',
      '.rs': 'text/x-rust',
      '.swift': 'text/x-swift',
      '.kt': 'text/x-kotlin',
      '.scala': 'text/x-scala',
      '.r': 'text/x-r',
      '.matlab': 'text/x-matlab',
      '.m': 'text/x-objective-c',
      '.pl': 'text/x-perl',
      '.sh': 'text/x-sh',
      '.ps1': 'text/x-powershell',
      '.json': 'application/json',
      '.xml': 'application/xml',
      '.yaml': 'text/yaml',
      '.yml': 'text/yaml',
      '.toml': 'text/x-toml',
      '.ini': 'text/plain',
      '.cfg': 'text/plain',
      '.conf': 'text/plain',
      '.sql': 'text/x-sql',
      '.bat': 'text/x-msdos-batch',
      '.cmd': 'text/x-msdos-batch',
      '.dockerfile': 'text/x-dockerfile',
      '.makefile': 'text/x-makefile',
      
      // 其他
      '.log': 'text/plain',
      '.rtf': 'application/rtf',
      '.tex': 'text/x-tex',
      '.epub': 'application/epub+zip',
      '.mobi': 'application/x-mobipocket-ebook'
    };
    return mimeTypes[ext] || 'application/octet-stream';
  }

  // 检查存储配额
  async checkStorageQuota(userId, fileSize) {
    // 尝试两个可能的表名
    let quota = await query(
      'SELECT total_quota, used_quota FROM storage_quotas WHERE user_id = ?',
      [userId]
    );

    if (quota.length === 0) {
      // 尝试另一个表名
      quota = await query(
        'SELECT total_quota, used_quota FROM user_storage_quotas WHERE user_id = ?',
        [userId]
      );
    }

    if (quota.length === 0) {
      // 创建默认配额，尝试两个表
      try {
        await query(
          'INSERT INTO storage_quotas (user_id, total_quota, used_quota) VALUES (?, ?, ?)',
          [userId, 10737418240, 0] // 10GB
        );
      } catch (error) {
        // 如果第一个表不存在，尝试第二个
        await query(
          'INSERT INTO user_storage_quotas (user_id, total_quota, used_quota) VALUES (?, ?, ?)',
          [userId, 10737418240, 0] // 10GB
        );
      }
      return { canUpload: true, remaining: 10737418240 };
    }

    const { total_quota, used_quota } = quota[0];
    const remaining = total_quota - used_quota;
    
    return {
      canUpload: fileSize <= remaining,
      remaining,
      total: total_quota,
      used: used_quota
    };
  }

  // 更新存储配额
  async updateStorageQuota(userId, fileSize, operation = 'add') {
    const change = operation === 'add' ? fileSize : -fileSize;
    try {
      await query(
        'UPDATE storage_quotas SET used_quota = used_quota + ?, file_count = file_count + ? WHERE user_id = ?',
        [change, operation === 'add' ? 1 : -1, userId]
      );
    } catch (error) {
      // 如果第一个表不存在，尝试第二个
      await query(
        'UPDATE user_storage_quotas SET used_quota = used_quota + ? WHERE user_id = ?',
        [change, userId]
      );
    }
  }

  // 创建文件夹
  async createFolder(userId, folderName, parentId = null) {
    try {
      console.log('创建文件夹 - userId:', userId, 'folderName:', folderName, 'parentId:', parentId);
      
      // 检查父文件夹是否存在
      if (parentId) {
        const parentFolder = await query(
          'SELECT id FROM cloud_files WHERE id = ? AND user_id = ? AND file_type = \'folder\'',
          [parentId, userId]
        );
        if (parentFolder.length === 0) {
          throw new Error('父文件夹不存在');
        }
      }

      // 生成文件夹路径
      const folderPath = parentId 
        ? `${parentId}/${folderName}`
        : folderName;

      // 创建文件夹记录
      const result = await query(
        'INSERT INTO cloud_files (user_id, parent_id, file_name, file_type, file_path, file_size, mime_type) VALUES (?, ?, ?, \'folder\', ?, 0, \'folder\')',
        [userId, parentId, folderName, folderPath]
      );

      // 更新文件夹计数
      try {
        await query(
          'UPDATE storage_quotas SET folder_count = folder_count + 1 WHERE user_id = ?',
          [userId]
        );
      } catch (error) {
        // 如果第一个表不存在，尝试第二个（可能没有folder_count字段）
        console.log('更新文件夹计数失败，可能表结构不同:', error.message);
      }

      console.log('文件夹创建成功:', result.insertId);
      return {
        success: true,
        folderId: result.insertId,
        folderPath
      };
    } catch (error) {
      console.error('创建文件夹失败:', error);
      return { success: false, error: error.message };
    }
  }

  // 上传文件
  async uploadFile(userId, file, folderId = null) {
    try {
      // 处理文件名编码问题
      const originalName = this.processFileName(file.originalname);
      console.log('处理后的文件名:', originalName);

      // 检查文件类型
      if (!this.isAllowedFileType(originalName)) {
        throw new Error('不支持的文件类型');
      }

      // 检查文件大小
      if (file.size > this.maxFileSize) {
        throw new Error('文件大小超过限制');
      }

      // 检查存储配额
      const quotaCheck = await this.checkStorageQuota(userId, file.size);
      if (!quotaCheck.canUpload) {
        throw new Error('存储空间不足');
      }

      // 生成文件信息
      const fileHash = this.generateFileHash(file.buffer);
      const uniqueFileName = this.generateUniqueFileName(originalName);
      const filePath = path.join(this.uploadPath, uniqueFileName);
      const mimeType = this.getMimeType(originalName);
      const fileExtension = path.extname(originalName).toLowerCase();

      // 保存文件到磁盘
      await fs.writeFile(filePath, file.buffer);

      // 检查是否已存在相同文件（基于文件名而不是哈希）
      const existingFile = await query(
        'SELECT id, file_name FROM cloud_files WHERE file_name = ? AND user_id = ? AND file_type = \'file\' AND parent_id = ?',
        [originalName, userId, folderId]
      );

      if (existingFile.length > 0) {
        // 删除刚保存的文件
        await fs.unlink(filePath);
        console.log('文件已存在，跳过上传:', existingFile[0].file_name);
        return {
          success: false,
          error: '文件已存在',
          existingFile: existingFile[0]
        };
      }

      // 保存文件记录到数据库
      const result = await query(
        `INSERT INTO cloud_files 
         (user_id, parent_id, file_name, file_type, 
          file_path, file_size, mime_type, file_hash) 
         VALUES (?, ?, ?, 'file', ?, ?, ?, ?)`,
        [userId, folderId, originalName, filePath, file.size, mimeType, fileHash]
      );

      // 更新存储配额
      await this.updateStorageQuota(userId, file.size, 'add');

      // 记录操作日志
      await this.logFileOperation(userId, result.insertId, 'upload', {
        fileName: originalName,
        fileSize: file.size,
        mimeType
      });

      return {
        success: true,
        fileId: result.insertId,
        fileName: originalName,
        fileSize: file.size,
        filePath
      };
    } catch (error) {
      console.error('文件上传失败:', error);
      return { success: false, error: error.message };
    }
  }

  // 获取用户文件列表
  async getUserFiles(userId, folderId = null, page = 1, limit = 20) {
    try {
      const offset = (page - 1) * limit;
      console.log('获取文件列表 - userId:', userId, 'folderId:', folderId);
      
      // 直接使用正确的字段名查询
      const files = await query(
        `SELECT f.*, fo.file_name as parent_folder_name
         FROM cloud_files f
         LEFT JOIN cloud_files fo ON f.parent_id = fo.id AND fo.file_type = 'folder'
         WHERE f.user_id = ? AND f.parent_id ${folderId ? '= ?' : 'IS NULL'} AND f.file_type = 'file'
         ORDER BY f.created_at DESC
         LIMIT ? OFFSET ?`,
        folderId ? [userId, folderId, limit, offset] : [userId, limit, offset]
      );

      const total = await query(
        `SELECT COUNT(*) as count FROM cloud_files WHERE user_id = ? AND parent_id ${folderId ? '= ?' : 'IS NULL'} AND file_type = 'file'`,
        folderId ? [userId, folderId] : [userId]
      );

      console.log('查询到的文件:', files.length, '个');
      return {
        success: true,
        files,
        total: total[0]?.count || 0,
        page,
        limit
      };
    } catch (error) {
      console.error('获取文件列表失败:', error);
      return { success: false, error: error.message };
    }
  }

  // 获取用户文件夹列表
  async getUserFolders(userId, parentId = null) {
    try {
      console.log('获取文件夹列表 - userId:', userId, 'parentId:', parentId);
      
      // 直接使用正确的字段名查询
      const folders = await query(
        `SELECT id, file_name as folder_name, parent_id, created_at, is_shared FROM cloud_files WHERE user_id = ? AND file_type = 'folder' AND parent_id ${parentId ? '= ?' : 'IS NULL'} ORDER BY created_at DESC`,
        parentId ? [userId, parentId] : [userId]
      );

      console.log('查询到的文件夹:', folders);
      return { success: true, folders };
    } catch (error) {
      console.error('获取文件夹列表失败:', error);
      return { success: false, error: error.message };
    }
  }

  // 重命名文件夹
  async renameFolder(userId, folderId, newName) {
    try {
      console.log('重命名文件夹 - userId:', userId, 'folderId:', folderId, 'newName:', newName);
      
      // 检查文件夹是否存在且属于当前用户
      const folder = await query(
        'SELECT id FROM cloud_files WHERE id = ? AND user_id = ? AND file_type = \'folder\'',
        [folderId, userId]
      );
      
      if (folder.length === 0) {
        return { success: false, message: '文件夹不存在' };
      }
      
      // 检查新名称是否已存在（在同一父文件夹下）
      const parentFolder = await query(
        'SELECT parent_id FROM cloud_files WHERE id = ?',
        [folderId]
      );
      
      const parentId = parentFolder[0].parent_id;
      const existingFolder = await query(
        `SELECT id FROM cloud_files WHERE user_id = ? AND file_type = 'folder' AND file_name = ? AND parent_id ${parentId ? '= ?' : 'IS NULL'} AND id != ?`,
        parentId ? [userId, newName, parentId, folderId] : [userId, newName, folderId]
      );
      
      if (existingFolder.length > 0) {
        return { success: false, message: '文件夹名称已存在' };
      }
      
      // 更新文件夹名称
      await query(
        'UPDATE cloud_files SET file_name = ? WHERE id = ? AND user_id = ?',
        [newName, folderId, userId]
      );
      
      console.log('文件夹重命名成功');
      return { success: true, message: '文件夹重命名成功' };
    } catch (error) {
      console.error('重命名文件夹失败:', error);
      return { success: false, error: error.message };
    }
  }

  // 删除文件夹
  async deleteFolder(userId, folderId) {
    try {
      console.log('删除文件夹 - userId:', userId, 'folderId:', folderId);
      
      // 检查文件夹是否存在且属于当前用户
      const folder = await query(
        'SELECT id FROM cloud_files WHERE id = ? AND user_id = ? AND file_type = \'folder\'',
        [folderId, userId]
      );
      
      if (folder.length === 0) {
        return { success: false, message: '文件夹不存在' };
      }
      
      // 检查文件夹是否为空（没有子文件夹和文件）
      const subFolders = await query(
        'SELECT id FROM cloud_files WHERE parent_id = ? AND file_type = \'folder\'',
        [folderId]
      );
      
      const subFiles = await query(
        'SELECT id FROM cloud_files WHERE parent_id = ? AND file_type = \'file\'',
        [folderId]
      );
      
      if (subFolders.length > 0 || subFiles.length > 0) {
        return { success: false, message: '文件夹不为空，无法删除' };
      }
      
      // 删除文件夹
      await query(
        'DELETE FROM cloud_files WHERE id = ? AND user_id = ?',
        [folderId, userId]
      );
      
      // 更新文件夹计数
      try {
        await query(
          'UPDATE storage_quotas SET folder_count = folder_count - 1 WHERE user_id = ?',
          [userId]
        );
      } catch (error) {
        console.log('更新文件夹计数失败，可能表结构不同:', error.message);
      }
      
      console.log('文件夹删除成功');
      return { success: true, message: '文件夹删除成功' };
    } catch (error) {
      console.error('删除文件夹失败:', error);
      return { success: false, error: error.message };
    }
  }

  // 删除文件
  async deleteFile(userId, fileId) {
    try {
      const file = await query(
        'SELECT * FROM cloud_files WHERE id = ? AND user_id = ? AND file_type = \'file\'',
        [fileId, userId]
      );

      if (file.length === 0) {
        throw new Error('文件不存在');
      }

      // 直接删除记录
      await query(
        'DELETE FROM cloud_files WHERE id = ?',
        [fileId]
      );

      // 更新存储配额
      await this.updateStorageQuota(userId, file[0].file_size, 'subtract');

      // 记录操作日志
      await this.logFileOperation(userId, fileId, 'delete', {
        fileName: file[0].file_name,
        fileSize: file[0].file_size
      });

      return { success: true };
    } catch (error) {
      console.error('删除文件失败:', error);
      return { success: false, error: error.message };
    }
  }

  // 重命名文件
  async renameFile(userId, fileId, newName) {
    try {
      const file = await query(
        'SELECT * FROM cloud_files WHERE id = ? AND user_id = ? AND file_type = \'file\'',
        [fileId, userId]
      );

      if (file.length === 0) {
        throw new Error('文件不存在');
      }

      await query(
        'UPDATE cloud_files SET file_name = ?, updated_at = NOW() WHERE id = ?',
        [newName, fileId]
      );

      // 记录操作日志
      await this.logFileOperation(userId, fileId, 'rename', {
        oldName: file[0].file_name,
        newName
      });

      return { success: true };
    } catch (error) {
      console.error('重命名文件失败:', error);
      return { success: false, error: error.message };
    }
  }

  // 移动文件
  async moveFile(userId, fileId, newFolderId) {
    try {
      const file = await query(
        'SELECT * FROM cloud_files WHERE id = ? AND user_id = ? AND file_type = \'file\'',
        [fileId, userId]
      );

      if (file.length === 0) {
        throw new Error('文件不存在');
      }

      // 检查目标文件夹是否存在
      if (newFolderId) {
        const folder = await query(
          'SELECT id FROM cloud_files WHERE id = ? AND user_id = ? AND file_type = \'folder\'',
          [newFolderId, userId]
        );
        if (folder.length === 0) {
          throw new Error('目标文件夹不存在');
        }
      }

      await query(
        'UPDATE cloud_files SET parent_id = ?, updated_at = NOW() WHERE id = ?',
        [newFolderId, fileId]
      );

      // 记录操作日志
      await this.logFileOperation(userId, fileId, 'move', {
        fileName: file[0].file_name,
        newFolderId
      });

      return { success: true };
    } catch (error) {
      console.error('移动文件失败:', error);
      return { success: false, error: error.message };
    }
  }

  // 创建文件分享链接
  async createFileShare(userId, fileId, shareType = 'private', password = null, expiresAt = null) {
    try {
      console.log('🔗 开始创建分享链接...');
      console.log('📋 参数信息:', {
        userId,
        fileId,
        shareType,
        hasPassword: !!password,
        expiresAt: expiresAt || '永不过期'
      });

      // 检查文件是否存在
      console.log('🔍 检查文件是否存在...');
      const file = await query(
        'SELECT * FROM cloud_files WHERE id = ? AND user_id = ? AND file_type = \'file\'',
        [fileId, userId]
      );

      if (file.length === 0) {
        console.error('❌ 文件不存在 - fileId:', fileId, 'userId:', userId);
        throw new Error('文件不存在');
      }

      console.log('✅ 文件存在:', {
        fileId: file[0].id,
        fileName: file[0].file_name,
        fileSize: file[0].file_size
      });

      // 生成分享令牌
      const shareToken = crypto.randomBytes(32).toString('hex');
      console.log('🎫 生成分享令牌:', shareToken.substring(0, 16) + '...');
      
      // 根据实际的表结构，file_shares表没有share_type字段
      // 使用password字段来判断分享类型：有密码为password类型，无密码为public类型
      console.log('💾 保存分享记录到数据库...');
      const result = await query(
        'INSERT INTO file_shares (file_id, user_id, share_token, share_password, expires_at) VALUES (?, ?, ?, ?, ?)',
        [fileId, userId, shareToken, password, expiresAt]
      );

      const shareUrl = `${process.env.FRONTEND_URL || 'http://localhost:3000'}/share/${shareToken}`;
      
      console.log('🎉 分享链接创建成功!');
      console.log('📊 分享信息:', {
        shareId: result.insertId,
        shareToken: shareToken.substring(0, 16) + '...',
        shareUrl,
        hasPassword: !!password,
        expiresAt: expiresAt || '永不过期'
      });

      return {
        success: true,
        shareToken,
        shareUrl
      };
    } catch (error) {
      console.error('❌ 创建分享链接失败:', error);
      console.error('📋 错误详情:', {
        message: error.message,
        stack: error.stack
      });
      return { success: false, error: error.message };
    }
  }

  // 记录文件操作日志
  async logFileOperation(userId, fileId, operationType, details = {}) {
    try {
      // 检查表结构，使用正确的字段名
      await query(
        'INSERT INTO file_operations (user_id, file_id, operation_type, operation_data) VALUES (?, ?, ?, ?)',
        [userId, fileId, operationType, JSON.stringify(details)]
      );
    } catch (error) {
      console.error('记录操作日志失败:', error);
    }
  }

  // 获取存储统计信息
  async getStorageStats(userId) {
    try {
      console.log('获取存储统计信息 - userId:', userId);
      
      // 尝试两个可能的表名
      let quota = await query(
        'SELECT * FROM storage_quotas WHERE user_id = ?',
        [userId]
      );

      if (quota.length === 0) {
        quota = await query(
          'SELECT * FROM user_storage_quotas WHERE user_id = ?',
          [userId]
        );
      }

      // 直接使用正确的字段名查询文件统计
      const fileStats = await query(
        `SELECT 
           COUNT(*) as total_files,
           SUM(file_size) as total_size,
           AVG(file_size) as avg_size
         FROM cloud_files 
         WHERE user_id = ? AND file_type = 'file'`,
        [userId]
      );

      // 查询文件夹统计
      const folderStats = await query(
        `SELECT COUNT(*) as total_folders
         FROM cloud_files 
         WHERE user_id = ? AND file_type = 'folder'`,
        [userId]
      );

      const recentFiles = await query(
        `SELECT file_name, file_size, created_at 
         FROM cloud_files 
         WHERE user_id = ? AND file_type = 'file' 
         ORDER BY created_at DESC 
         LIMIT 5`,
        [userId]
      );

      // 计算实际使用的存储空间和数量
      const actualUsedQuota = fileStats[0]?.total_size || 0;
      const actualFileCount = fileStats[0]?.total_files || 0;
      const actualFolderCount = folderStats[0]?.total_folders || 0;
      
      // 更新配额表中的实际使用量
      if (quota.length > 0) {
        await query(
          'UPDATE storage_quotas SET used_quota = ?, file_count = ?, folder_count = ? WHERE user_id = ?',
          [actualUsedQuota, actualFileCount, actualFolderCount, userId]
        );
      }

      console.log('统计信息查询结果:', {
        quota: quota[0],
        fileStats: fileStats[0],
        folderStats: folderStats[0],
        recentFiles,
        actualUsedQuota,
        actualFileCount,
        actualFolderCount
      });

      return {
        success: true,
        quota: {
          ...quota[0],
          used_quota: actualUsedQuota,
          file_count: actualFileCount,
          folder_count: actualFolderCount
        },
        stats: fileStats[0] || { total_files: 0, total_size: 0, avg_size: 0 },
        recentFiles
      };
    } catch (error) {
      console.error('获取存储统计失败:', error);
      return { success: false, error: error.message };
    }
  }
}

module.exports = new CloudStorageService();
